clear
set more off
set matsize 2000
set scheme lean2

*	Change CD
*	global root         	"..."
	global source			="$root/raw"
	global temp				="$root/temp"
	global code				="$root/code"
	global output			="$root/output"
	

*This do-files merges the different datasets and generates the key variables
	
use "$temp/swedish_elections", replace

merge m:1 kommun county using "$temp/sweden_part"
drop _merge

merge m:1 kommun county using "$temp/sweden_tax"
drop _merge

*Add IV 
*(Recall: 1 - very high , 8 - not suitable at all --> higher value less good)
merge m:1 ref_code using  "$temp/sweden_iv"
keep if _merge==3

encode county, gen(county_id)

foreach var in conservative_e left_e turnout s_largefarms s_noble {
	replace `var' = `var'*100
}

bys kommun county: gen number = _N
drop if number==1
drop number

egen totalbyid = total(!missing(conservative_e)), by(kommun county)
keep if totalbyid==12
drop totalbyid

gen s_agri_1930 = empl1930_agri / empl1930_tot

gen s_agriculture = .
	replace s_agriculture = emplsh1910_agri  if year<1930
	replace s_agriculture = agriemplshare1930 if year>1929
	
keep kommun left_e conservative_e turnout nazi_e s_largefarms avg_suitability s_noble toppfyrk toppagrarianfyrk popdensity s_agriculture year county county_id

rename kommun municipality

label var municipality "Municipality name"
label var conservative_e "Conservatives (in \%)"
label var county "County name"
label var county_id "County ID"
label var left_e "Left (in \%)"
label var nazi_e "Nazi (in \%)"
label var popdensity "Population density"
label var s_agriculture "Employment agriculture (in \%)"
label var turnout "Turnout (in \%)"
label var year "Year"
label var toppfyrk "Share income and wealth tax paid by top taxpayer"
label var toppagrarianfyrk "Share income and wealth tax, for agrarian income and wealth, paid by top taxpayer"
label var s_largefarms "Large farmers among farmers (in \%)"
label var avg_suitability "Soil suitability"
label var s_noble "Land owned by nobility (in \%)"	

order municipality year county county_id conservative_e turnout left_e nazi_e s_largefarms s_noble s_agriculture popdensity avg_suitability

save "$temp/sweden_final", replace
